import Vue from 'vue';
import common from "@/common/common.js";
import config from "@/common/config.js"; //此变量只能写在方法里,全局会报错

var $notify = null;
var heartTime = 30000;
var reStartTimeout = 5000;

function openMsg(msg, urlTile, url) {
	if ($notify != null) {
		$notify.close();
	}
	var json = {
		title: '提示',
		message: msg,
		duration: 0,
		type: "info",
		offset: window.innerHeight - 120
	};
	if (!!urlTile && !!url) {
		json.onClick = function() {
			window.app.$router.push(url);
			if ($notify != null) {
				$notify.close();
				$notify = null;
			}
		};
		json.customClass = "customStyle";
	}
	$notify = window.app.$notify(json);
}

function start() {
	startWebSocket();
}

var websocket = null;

//发送消息
function send(msg, callback) {
	if (websocket == null) return;
	try {
		//这里无法捕获异常
		websocket.send(msg);
	} catch (e) {
		console.log("websocket发送失败", e);
		reStartWebSocket();
		return;
	}
	if (callback != null && typeof(callback) == 'function') callback();
}

//关闭WebSocket连接
function closeWebSocket() {
	if (websocket != null) {
		try {
			websocket.onerror = function(e) {
				console.log("closeWebSocket", e);
			};
			websocket.onopen = function() {};
			websocket.onclose = function(e) {
				console.log("closeWebSocket", e);
			};
			websocket.onmessage = function() {};
			websocket.close();
		} catch (e) {
			console.log("closeWebSocket出错:", e);
		}
		websocket = null;
	}
}

function startWebSocket(callback) {
	//判断当前浏览器是否支持WebSocket
	if ('WebSocket' in window) {
		if (websocket != null && websocket.readyState == 1) {
			console.log("websocket已经连接成功");
			return;
		}
		closeWebSocket();
		var val = common.getToken();
		var json = null;
		if (!!val) {
			try {
				json = JSON.parse(val);
			} catch (e) {}
		}
		if (json == null || json.token == null) {
			return;
		}
		var interfaceUrl = config.webapiUrl;
		var ws = interfaceUrl.indexOf("https") == 0 ? "wss" : "ws";
		var startUrl = '';
		if (interfaceUrl.indexOf("localhost") != -1) {
			startUrl = ws + "://localhost:" + config.websocketChatPort + "/Chat";
		} else {
			startUrl = ws + "://" + interfaceUrl.replace("http://", "").replace("https://", "") + ":" +
				config.websocketChatPort + "/Chat";
		}
		startUrl = startUrl + "?" + config.tokenKey + "=" + encodeURIComponent(json.token);
		//这里无法捕获异常
		websocket = new WebSocket(startUrl);
		window.websocketObj = websocket;
	} else {
		alert("当前浏览器不支持websocket");
		return;
	}
	if (websocket == null) return;
	//连接发生错误的回调方法
	websocket.onerror = function(e) {
		//showMsg("WebSocket连接发生错误");
		console.log("websocket连接失败", e);
		reStartWebSocket(callback);
	};

	websocket.onopen = function() {
		console.log("websocket连接成功");

		startHeartSend();
	};

	//接收到消息的回调方法
	websocket.onmessage = function(event) {
		try {
			console.log("websocket.onmessage:", event.data);
			//如果在订单ID的那个页面
			var json = JSON.parse(event.data);
			if (json.EnumWebSocketMessage == 100) { //进度条
				var json = JSON.parse(event.data);
				window.appMain.showProcess(json.Message, json.Result.Percent);
				if (!!json.Result.Url) {
					window.open(json.Result.Url);
				}
			} else if (json.EnumChatSendType == 0) { //普通消息
				common.baseVM.methods.showMsg(json.Message);
			} else if (json.EnumChatSendType == 1) { //更新状态消息
			} else if (json.EnumChatSendType == 1) { //右下角弹窗消息
				openMsg(json.Message, json.Result.Title, json.Result.Url);
			}
		} catch (e) {
			console.log("websocket.onmessage异常:", event, e);
		}
	}

	//连接关闭的回调方法
	websocket.onclose = function(e) {
		console.log("websocket断开成功", e);
		reStartWebSocket();
	}
}

var setTimeoutObj = null;

function reStartWebSocket(callback) {
	if (setTimeoutObj != null) {
		clearTimeout(setTimeoutObj);
		setTimeoutObj = null;
	}
	setTimeoutObj = setTimeout(function() {
			//这里无法捕获异常
			startWebSocket(callback);
		},
		reStartTimeout);
}

function webSocketConnected() {
	if (websocket != null) {
		return true;
	}
	return false;
}

var setIntervalObj = null;

function startHeartSend() {
	if (setIntervalObj != null) {
		clearInterval(setIntervalObj);
		setIntervalObj = null
	}
	setIntervalObj = setInterval(() => {
		//console.log("心跳执行,发送空的");
		send("");
	}, heartTime);
}

export default {
	start,
	webSocketConnected,
	send,
	websocket
}
